<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">  <!-- 设置字符编码为 UTF-8 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>主页</title>
    <link rel="icon" href="/img/favicon.png" type="image/png">
    <script src="libs/axios.min.js"></script>
    <script src="libs/vue.global.js"></script>
    <script src="libs/index.full.js"></script>
    <script src="libs/index.iife.js"></script>
    <script src="libs/stomp.min.js"></script>
    <script src="libs/sockjs.min.js"></script>
    <script src="js/navbar.js"></script>
    <link rel="stylesheet" href="libs/index.css">
    <link rel="stylesheet" href="css/navbar.css">
    <link rel="stylesheet" href="css/index.css">

</head>
<body>
<div id="app" class="full_container">
    <div id="navbar" class="navbar"></div>
    <div class="app_container">
        <div class="wrapper">
            <div class="item1">
                <el-carousel class="carousel-container" trigger="click" height="100%">
                    <el-carousel-item class="carousel-container-item" v-for="(image, index) in images" :key="index">
                        <img class="carousel-container-img" :src="image" alt="轮播图片" @click="openLink(index)">
                    </el-carousel-item>
                </el-carousel>
                <div class="carousel-div"></div>
            </div>
            <div class="item2">
                <img src="img/PostsArticles.jpg" class="item-img">
                <div class="item-div1">
                    <el-text class="text-container" truncated>
                        {{postsArticles[0].text}}
                    </el-text>
                    <div class="item-div2">
                        <el-tag class="tag" type="warning">点赞 2466</el-tag>
                        <span class="text-span">{{postsArticles[0].author}} · {{postsArticles[0].releaseTime}}</span>
                    </div>
                </div>
            </div>
            <div class="item3">
                <img src="img/Articles5.jpg" class="item-img">
                <div class="item-div1">
                    <el-text class="text-container" truncated>
                        {{postsArticles[3].text}}
                    </el-text>
                    <div class="item-div2">
                        <el-tag class="tag" type="warning">点赞 2466</el-tag>
                        <span class="text-span">{{postsArticles[3].author}} · {{postsArticles[3].releaseTime}}</span>
                    </div>
                </div>
            </div>
            <div class="item4">
                <img src="img/Articles6.jpg" class="item-img">
                <div class="item-div1">
                    <el-text class="text-container" truncated>
                        {{postsArticles[1].text}}
                    </el-text>
                    <div class="item-div2">
                        <el-tag class="tag" type="warning">点赞 2466</el-tag>
                        <span class="text-span">{{postsArticles[1].author}} · {{postsArticles[1].releaseTime}}</span>
                    </div>
                </div>
            </div>
            <div class="item5">
                <img src="img/Articles7.jpg" class="item-img">
                <div class="item-div1">
                    <el-text class="text-container" truncated>
                        {{postsArticles[2].text}}
                    </el-text>
                    <div class="item-div2">
                        <el-tag class="tag" type="warning">点赞 2466</el-tag>
                        <span class="text-span">{{postsArticles[2].author}} · {{postsArticles[2].releaseTime}}</span>
                    </div>
                </div>
            </div>
            <div class="item6">
                <img :src="Articles[0]?.imageUrl" class="item-img">
                <div class="item-div1">
                    <el-text class="text-container" truncated>
                        {{Articles[0]?.title}}
                    </el-text>
                    <div class="item-div2">
                        <el-tag class="tag" type="warning">点赞 {{Articles[0]?.likes}}</el-tag>
                        <span class="text-span">{{Articles[0]?.author}} · {{formatTime(Articles[0]?.publishedAt) }}</span>
                    </div>
                </div>
            </div>
            <div class="item7">
                <img :src="Articles[1]?.imageUrl" class="item-img">
                <div class="item-div1">
                    <el-text class="text-container" truncated>
                        {{Articles[1]?.title}}
                    </el-text>
                    <div class="item-div2">
                        <el-tag class="tag" type="warning">点赞 {{Articles[1]?.likes}}</el-tag>
                        <span class="text-span">{{Articles[1]?.author}} · {{formatTime(Articles[1]?.publishedAt) }}</span>
                    </div>
                </div>
            </div>
            <div class="item8">
                <img :src="Articles[2]?.imageUrl" class="item-img">
                <div class="item-div1">
                    <el-text class="text-container" truncated>
                        {{Articles[2]?.title}}
                    </el-text>
                    <div class="item-div2">
                        <el-tag class="tag" type="warning">点赞 {{Articles[2]?.likes}}</el-tag>
                        <span class="text-span">{{Articles[2]?.author}} · {{formatTime(Articles[2]?.publishedAt) }}</span>
                    </div>
                </div>
            </div>
            <div class="item9">
                <img :src="Articles[3]?.imageUrl" class="item-img">
                <div class="item-div1">
                    <el-text class="text-container" truncated>
                        {{Articles[3]?.title}}
                    </el-text>
                    <div class="item-div2">
                        <el-tag class="tag" type="warning">点赞 {{Articles[3]?.likes}}</el-tag>
                        <span class="text-span">{{Articles[3]?.author}} · {{formatTime(Articles[3]?.publishedAt) }}</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <el-badge :is-dot="hasUnreadMessage" :offset="[-5,5]" class="wechat">
        <img class="wechat" src="img/聊天.png" @click="chat">
    </el-badge>
    <el-dialog v-model="chatDialogVisible" class="chat-dialog">
        <div class="chat-dialog-left">
            <div
                    class="contact"
                    v-for="(contact, index) in contacts"
                    :key="index"
                    :class="{ 'selected': selectedIndex === index }"
                    @click="selectContact(index)"
            >
                <el-badge :is-dot="!contact.isRead" :offset="[-10, 0]" >
                    <img :src="contact.sendAvatar" class="contact-avatar" alt="头像"/>
                </el-badge>
                <div class="contact-info">
                    <div class="contact-name">{{ contact.sender }}</div>
                    <div class="contact-message">
                        <div class="message-content">{{ contact.message }}</div>
                        <div class="message-time">{{ formatTime(contact.timestamp) }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="chat-dialog-right">
            <div class="chat-dialog-right-header">{{selectedContact}}</div>
            <div class="chat-dialog-right-main">
                <div class="message-right-container"ref="chatContainer">
                    <div v-for="(message, index) in processedMessages" :key="index"
                         :class="{'friend': message.isFriend, 'self': !message.isFriend}">
                        <div :class="{'message-right-content-friend': message.isFriend, 'message-right-content-self': !message.isFriend}">
                            <!--                            <div class="message-right-avatar">-->
                            <!--                                <img :src="message.avatar" :alt="message.isFriend ? '好友头像' : '自己头像'" @click="togglePopover(index)">-->
                            <!--                            </div>-->

                            <!-- 个人信息弹出框 -->
                            <el-popover
                                    :ref="'popover-' + index"
                                    placement="right-start"
                                    trigger="manual"
                                    popper-class="custom-popover"
                                    v-model:visible="popovers[index]"
                            >
                                <template #reference>
                                    <div class="message-right-avatar">
                                        <img :src="message.sendAvatar" :alt="message.isFriend ? '好友头像' : '自己头像'"
                                             @click="togglePopover(message,index)">
                                    </div>
                                </template>
                                <div class="user-info">
                                    <div class="user-info-header">
                                        <div class="user-info-header-left">
                                            <img :src="userInfo.avatar" class="user-info-avatar">
                                        </div>
                                        <div class="user-info-header-right">
                                            <div class="user-info-remark">{{ userInfo.remark }}</div>
                                            <div class="user-info-nickname">昵称:{{ userInfo.nickname }}</div>
                                            <div class="user-info-username">微信号:{{ userInfo.username }}</div>
                                            <div class="user-info-area">地区:{{ userInfo.area }}</div>
                                        </div>
                                    </div>
                                    <div class="user-info-remark-area">
                                        <div class="user-info-remark2">
                                            <span class="remark-label1">备注</span>
                                            <span class="remark-content1">{{ userInfo.remark }}</span>
                                        </div>
                                    </div>
                                    <div class="user-info-signature-area">
                                        <div class="user-info-signature">
                                            <span class="remark-label2">个性签名</span>
                                            <span class="remark-content2">{{ userInfo.signature }}</span>
                                            </span></div>
                                    </div>
                                    <div class="user-info-icon-area">
                                        <img class="icon-img1" src="/img/发消息.png">
                                        <img class="icon-img2" src="/img/语音聊天.png">
                                        <img class="icon-img3" src="/img/视频聊天.png">
                                    </div>
                                </div>
                            </el-popover>
                            <div class="message-right-bubble">
                                <p>{{ message.message }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="chat-dialog-right-footer">
                <div class="footer-functional-area">
                    <el-popover placement="top-start" :width="300" trigger="click" v-model:visible="emojiVisible">
                        <template #reference>
                            <img class="footer-functional-area-img" src="/img/表情.png">
                        </template>
                        <div class="emoji-container">
                        <span v-for="emoji in emojis" :key="emoji" class="emoji-item" @click="insertEmoji(emoji)">
                          {{ emoji }}
                        </span>
                        </div>
                    </el-popover>
                </div>
                <div class="footer-input">
                    <el-input class="footer-input-area"
                              v-model="inputMessage"
                              type="textarea"
                              :autosize="{ minRows: 5, maxRows: 5 }"
                              ref="messageInput">
                    </el-input>
                </div>
                <div class="footer-send">
                    <el-button class="footer-send-button" type="success" @click="sendPrivateMessage">发送</el-button>
                </div>
            </div>
        </div>
    </el-dialog>
    <el-dialog
            v-model="noticeVisible"
            width="500px"
            :show-close="false"
            center
            class="notice-dialog"
    >
        <div class="dialog-header">
            <el-icon><bell-filled /></el-icon>
            <span class="dialog-title">系统公告</span>
        </div>

        <div class="dialog-content" style="white-space: pre-wrap; ">
            {{notice.content}}
        </div>

        <div class="dialog-footer">
            <el-button type="primary" @click="noticeVisible = false">我知道了</el-button>
        </div>
    </el-dialog>
</div>
<script>
    const {createApp} = Vue;

    const {ElMessage} = ElementPlus;

    const app =createApp({
        data() {
            return {
                images: [
                    'img/CarouselImage1.jpg',
                    'img/CarouselImage2.jpg',
                    'img/CarouselImage3.jpg',
                    'img/CarouselImage4.jpg',
                    'img/CarouselImage5.jpg',
                    'img/CarouselImage6.jpg',
                ],
                CarouselImageUrl: [
                    "https://www.bilibili.com/video/BV1cv4y147kE?t=3.4",
                    "https://www.bilibili.com/video/BV1UG41127tH?t=32.6",
                    "https://www.bilibili.com/video/BV1Lg4FenE1y?t=2.9",
                    "https://www.bilibili.com/video/BV1ww4m1274m?t=4.1",
                    "https://www.bilibili.com/video/BV1M94y1G7Rp?t=3.0",
                    "https://www.bilibili.com/video/BV14b421J7Ge?t=2.7"
                ],
                postsArticles: [
                    {
                        text: "中药+为什么能成为年轻人的养生新招式？想要知道原因，快来和我一起揭秘中药对于养生各种不为人知的秘密吧！",
                        author: '章初初',
                        releaseTime: '8小时前'
                    },
                    {
                        text: "如何保持健康的生活习惯？",
                        author: '李明',
                        releaseTime: '2天前'
                    },
                    {
                        text: "运动对身心健康的影响",
                        author: '王小红',
                        releaseTime: '1周前'
                    },
                    {
                        text: "养生新趋势：枸杞奶茶为何成了年轻人的最爱？探索传统滋补与现代饮品的完美结合，解锁健康新方式！",
                        author: "李然然",
                        releaseTime: "5小时前"
                    }
                ],
                Articles:[],
                chatDialogVisible: false,
                selectedIndex: null, // 记录选中的联系人
                contacts: [],//好有列表
                currentUser: null,//登录的人的昵称
                currentUserAvatar: null,//登录的人的头像
                selectedContact: '睡觉大王',//联系人昵称
                selectedContactAvatar: null,//联系人头像
                popovers: [],
                messages: [],
                inputMessage: '',
                emojiVisible: false, // 控制表情选择框显示
                emojis: ["😀", "😁", "😂", "🤣", "😃", "😄", "😅", "😆", "😉", "😊", "😋", "😎", "😍", "😘", "🥰",
                    "😗", "😙", "😚", "🙂", "🤗", "🤩", "🤔", "🤨", "😐", "😑", "😶", "🙄", "😏", "😣", "😥",
                    "😮", "🤐", "😯", "😪", "😫", "🥱", "😴", "😌", "😛", "😜", "😝", "🤤", "😒", "😓", "😔",
                    "🤑", "🤠", "😈", "👿", "🤡", "💀", "👽", "👾", "🤖", "💩", "😺", "😸", "😹", "😻", "😼",
                    "😽", "🙀", "😿", "😾", "🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼", "🐨", "🐯", "🦁",
                    "🐮", "🐷", "🐸", "🐵", "🙈", "🙉", "🙊", "🐒", "🐔", "🐧", "🐦", "🐤", "🐣", "🐥", "🦆",
                    "🦅", "🦉", "🦇", "🐺", "🐗", "🐴", "🦄", "🐝", "🐛", "🦋", "🐌", "🐞", "🐜", "🦗", "🕷",
                    "🕸", "🐢", "🐍", "🦎", "🦖", "🦕", "🐙", "🦑", "🦞", "🦀", "🐡", "🐠", "🐟", "🐬", "🐳",
                    "🐋", "🦈", "🐊", "🐆", "🐅", "🐃", "🐂", "🐄", "🦌", "🐪", "🐫", "🦙", "🦒", "🐘", "🦏",
                    "🦛", "🐁", "🐀", "🐿", "🦔", "🐉", "🐲", "🌵", "🎄", "🌲", "🌳", "🌴", "🌱", "🌿", "☘",
                    "🍀", "🎍", "🎋", "🍃", "🍂", "🍁", "🌾", "🌺", "🌻", "🌹", "🥀", "💐", "🌷", "🌼", "🌸"],
                userInfos: [
                    {
                        avatar: 'img/avatar1.jpg',
                        nickname: '睡觉大王',
                        username: 'shuijiaodawang',
                        signature: '爱与不爱皆自由',
                        area: '浙江 杭州',
                        sex: '女',
                        remark: '睡觉王',
                    }
                ],
                personName:null,//头像对应的昵称
                userInfo: {},
                stompClient: null,
                socket: null,
                showDot: true,
                noticeVisible: false,
                notice:[],
                permissionLevel:0,
            };
        },
        computed: {
            processedMessages() {
                return this.messages.map(msg => {
                    const isSelf = msg.sender === this.currentUser;

                    return {
                        ...msg,
                        isFriend: !isSelf, // sender 不是当前用户，则是好友
                    };
                });
            },
            hasUnreadMessage() {
                const unread = this.contacts.some(contact => contact.isRead === false);
                console.log('Has unread message:', unread);  // 调试
                return unread;
            }
        },
        created() {
            this.getCurrentUser();
            this.getTop4Articles();
            this.getNotice();
            this.popovers = new Array(this.messages.length).fill(false);
        },
        mounted() {
            this.connect();
            // 获取 URL 参数
            const urlParams = new URLSearchParams(window.location.search);
            const noticeParam = urlParams.get('noticeVisible');

            // 判断是否显示公告
            if (noticeParam === 'true') {
                this.noticeVisible = true;
            } else {
                this.noticeVisible = false;
            }
        },
        methods: {
            formatTime(timestamp) {
                const now = new Date();
                const messageDate = new Date(timestamp);

                const year = messageDate.getFullYear();
                const month = String(messageDate.getMonth() + 1).padStart(2, '0');
                const day = String(messageDate.getDate()).padStart(2, '0');
                const hours = String(messageDate.getHours()).padStart(2, '0');
                const minutes = String(messageDate.getMinutes()).padStart(2, '0');
                const seconds = String(messageDate.getSeconds()).padStart(2, '0');

                // 计算时间差
                const diffTime = now - messageDate;
                const diffDays = Math.floor(diffTime / (1000 * 3600 * 24)); // 转换为天数

                if (diffDays === 0) {
                    // 如果在今天，返回时分秒
                    return `${hours}:${minutes}`;
                } else if (diffDays === 1) {
                    // 如果昨天，返回“昨天”
                    return `昨天 `;
                } else {
                    // 如果超过昨天，返回日期 (MM/DD/YY)
                    return `${String(year).slice(2)}/${month}/${day}`;
                }
            },
            // 获取点赞数最多的前四篇文章部分内容
            getTop4Articles(){
                axios.get('http://localhost:8080/article/top4')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.Articles = response.data.data;
                        } else {
                            ElMessage.error("首页文章获取失败");
                        }
                    })
                    .catch(error => console.error("首页文章获取失败:", error));
            },
            // 获取当前用户
            getCurrentUser() {
                axios.get('http://localhost:8080/chat/currentUser')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.currentUser = response.data.data.nickname;
                            this.currentUserAvatar = response.data.data.avatar;
                            this.permissionLevel = response.data.data.permissionLevel;
                            this.getFriendsList(); // 在获取用户后，再加载好友列表
                        } else {
                            console.warn("未登录，跳转到登录页");
                            window.location.href = "/login.html"; // 重定向到登录页
                        }
                    })
                    .catch(error => console.error("获取当前用户失败:", error));
            },
            // 获取好友列表
            getFriendsList() {
                axios.get('http://localhost:8080/chat/friends', {
                    params: {recipient: this.currentUser}
                }).then(response => {
                    if (response.data.code === 200) {
                        this.contacts = response.data.data;
                    }
                }).catch(error => {
                    console.error("获取好友列表失败:", error);
                });
            },

            // 获取聊天记录
            getChatHistory(friend,showDialog) {
                axios.get('http://localhost:8080/chat/history', {
                    params: {sender: this.currentUser, recipient: friend}
                }).then(response => {
                    if (response.data.code === 200) {
                        this.messages = response.data.data;
                        if(showDialog){
                            this.markAsRead(friend);
                        }

                    }
                }).catch(error => {
                    console.error("获取聊天记录失败:", error);
                });

            },
            // 获取个人信息
            getUserProfile(nickname) {
                axios.get('http://localhost::8080/chat/userProfile', {
                    params: {nickname: this.personName}
                }).then(response => {
                    if (response.data.code === 200) {
                        this.userInfo = response.data.data;
                    }
                }).catch(error => {
                    console.error("获取聊天记录失败:", error);
                });
            },

            // 选择好友并获取聊天记录
            selectFriend(friend) {
                this.activeFriend = friend;
                this.getChatHistory(friend,this.chatDialogVisible);
            },
            //已读
            markAsRead(contact) {
                axios.get("http://localhost:8080/chat/markAsRead", {
                    params: {sender: contact,recipient: this.currentUser}
                }).then(response => {
                    if (response.data.code === 200) {
                        console.log(`所有来自 ${contact} 的消息已标记为已读`);
                        this.getFriendsList(); // 刷新好友列表，更新未读红点状态
                    }
                }).catch(error => {
                    console.error("标记消息为已读失败:", error);
                });
            },

            openLink(index) {
                const url = this.CarouselImageUrl[index];
                if (url) {
                    window.open(url, '_blank');
                }
            },
            chat() {
                if(this.permissionLevel > 1){
                    this.chatDialogVisible = !this.chatDialogVisible;
                }else {
                    ElMessage.warning("对不起,您没有权限")
                }
            },
            selectContact(index) {
                this.selectedIndex = index;
                this.selectedContact = this.contacts[index].sender;
                this.selectedContactAvatar = this.contacts[index].sendAvatar;
                this.getChatHistory(this.selectedContact,this.chatDialogVisible);
                this.stompClient.unsubscribe();
                const destination = `/user/${this.selectedContact}/queue`; // 动态拼接路径
                this.stompClient.subscribe(destination, (messageOutput) => {
                    let receivedMessage = JSON.parse(messageOutput.body);
                    this.getChatHistory(this.selectedContact,this.chatDialogVisible);
                    this.scrollToBottom(); // 新消息后自动滚动
                });
                this.scrollToBottom();
            },
            togglePopover(message,index) {
                // 先关闭所有 popover，避免多个同时显示
                this.popovers = this.popovers.map(() => false);
                // 如果当前状态是 false，则设置为 true，反之亦然
                this.popovers[index] = !this.popovers[index];
                this.personName = message.sender;
                this.getUserProfile(this.personName);
                // const message = this.messages[index];

                // // 在 userInfos 里查找匹配的 avatar
                // this.userInfo = this.userInfos.find(user => user.avatar === message.avatar) || {};
            },
            // 切换表情选择框显示
            toggleEmojiPicker() {
                this.emojiVisible = !this.emojiVisible;
            },

            // 在输入框光标处插入表情
            insertEmoji(emoji) {
                const input = this.$refs.messageInput?.textarea; // 获取 el-input 内部的 textarea
                if (input) {
                    const start = input.selectionStart;
                    const end = input.selectionEnd;
                    this.inputMessage =
                        this.inputMessage.substring(0, start) + emoji + this.inputMessage.substring(end);
                    input.setSelectionRange(start + emoji.length, start + emoji.length); // 移动光标
                    input.focus(); // 重新聚焦输入框
                }
            },
            scrollToBottom() {
                this.$nextTick(() => {
                    setTimeout(() => {
                        const container = this.$refs.chatContainer;
                        if (container) {
                            container.scrollTop = container.scrollHeight;
                        }
                    }, 50);
                });
            },
            connect() {
                this.socket = new SockJS("chat");
                this.stompClient = Stomp.over(this.socket);
                this.stompClient.connect({}, () => {
                    // 使用动态路径进行订阅
                    const destination = `/user/${this.selectedContact}/queue`; // 动态拼接路径
                    this.stompClient.subscribe(destination, (messageOutput) => {
                        let receivedMessage = JSON.parse(messageOutput.body);
                        this.getChatHistory(this.selectedContact,this.chatDialogVisible);
                        this.getFriendsList();
                        this.scrollToBottom(); // 新消息后自动滚动
                    });
                }, (error) => {
                    console.log("WebSocket connection error:", error); // 连接错误日志
                });
            },
            sendPrivateMessage() {
                if (this.inputMessage.trim()) {
                    let messageData = {
                        sender: this.currentUser,
                        recipient: this.selectedContact,
                        message: this.inputMessage,
                        sendAvatar: this.currentUserAvatar,
                        recipientAvatar: this.selectedContactAvatar,
                    };
                    this.stompClient.send("/app/privateMessage", {}, JSON.stringify(messageData));
                    this.inputMessage = "";
                    this.getChatHistory(this.selectedContact,this.chatDialogVisible);
                    this.getFriendsList();
                    this.scrollToBottom();
                }
            },
            getNotice(){
                axios.get('http://localhost:8080/notice/getOne')
                    .then(response => {
                    if (response.data.code === 200) {
                        this.notice = response.data.data;
                    }
                }).catch(error => {
                    console.error("获取系统公告失败:", error);
                });
            }
        }
    })
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }
    app.use(ElementPlus).mount("#app");
</script>
</body>
</html>
